package cn.ryanpenn.es.springclound.service.impl;

import cn.ryanpenn.es.springclound.model.WeatherResponse;
import cn.ryanpenn.es.springclound.service.WeatherService;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * WeatherServiceImpl
 *
 * @author pennryan
 */
@Service
public class WeatherServiceImpl implements WeatherService {

    private final String WEATHER_BYNAME_API = "http://wthrcdn.etouch.cn/weather_mini?city=";
    private final String WEATHER_BYKEY_API = "http://wthrcdn.etouch.cn/weather_mini?citykey=";
    private final int TIMEOUT = 30 * 60;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    OkHttpClient okHttpClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public WeatherResponse getByCityCode(int code) {
        return queryWeather(WEATHER_BYKEY_API + code);
    }

    @Override
    public WeatherResponse getByCityName(String name) {
        return queryWeather(WEATHER_BYNAME_API + name);
    }

    private WeatherResponse queryWeather(String url) {
        String bodyStr = null;
        ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        if (stringRedisTemplate.hasKey(url)) {
            logger.info("从缓存中读取..." + url);
            bodyStr = ops.get(url);
        } else {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            try {
                Response response = okHttpClient.newCall(request).execute();
                ResponseBody body = response.body();
                if (body != null) {
                    bodyStr = body.string();
                    logger.info("写入缓存..." + url);
                    ops.set(url, bodyStr, TIMEOUT, TimeUnit.SECONDS);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (!StringUtils.isEmpty(bodyStr)) {
            try {
                return new ObjectMapper().readValue(bodyStr, WeatherResponse.class);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
